package com.woniuxy.automotivemanagementsystem.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.woniuxy.automotivemanagementsystem.entity.User;
import com.woniuxy.automotivemanagementsystem.entity.vo.UserVo;
import com.woniuxy.automotivemanagementsystem.service.UserService;
import com.woniuxy.automotivemanagementsystem.utils.JWT.JwtUtil;
import com.woniuxy.automotivemanagementsystem.utils.RedisUtil;
import com.woniuxy.automotivemanagementsystem.utils.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginController {
    @Autowired
    private RedisUtil redis;
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public Result login(@RequestBody UserVo vo, HttpServletResponse response){
        if(vo.getVerifyCode()== null || vo.getVerifyCode().trim().isEmpty()){
            return Result.error("验证码不能为空").code(521);
        }
        String code = redis.get(vo.getCodeId());
        if (code == null || code.isEmpty()){
            return Result.error("验证码已过期").code(522);
        }
        if(!code.equalsIgnoreCase(vo.getVerifyCode())){
            return Result.error("验证码错误").code(523);
        }else{
            User user = userService.login(vo.getUsername(), vo.getPassword());
            if (user== null){
                return Result.error("用户名或密码错误").code(524);
            }else{
                String token = JwtUtil.createToken(user);
                response.setHeader("token",token);
                response.setHeader("Access-Control-Expose-Headers","token");
                return Result.success(user);
            }
        }
    }

    @GetMapping("createCaptcha")
    public Result createCaptcha(String codeId){
        //定义Map集合封装返回数据
        Map<String,Object> map = new HashMap<>();
        //判断codeId是否为null  或者 空串
        if(codeId == null || codeId.trim().isEmpty()){
            //表示用户第一次获取验证，所以，随机生成一个唯一标识符
            codeId =  IdUtil.getSnowflakeNextIdStr();
        }

        //设置验证码图片长、宽、验证码字符数、干扰线宽度
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 30, 1, 10);
        //设置字体样式和大小
        lineCaptcha.setFont(new Font("仿宋", Font.BOLD, 30));
        //获取验证码
        String code = lineCaptcha.getCode();
        System.out.println(code);
        //把验证码保存到redis 缓存数据库
        redis.set(codeId, code,60);
        //转为Base64字符串
        String imageBase64 = lineCaptcha.getImageBase64Data();
        //封装响应数据
        map.put("codeId",codeId);
        map.put("imageBase64",imageBase64);
        return Result.success(map);
    }
}
